import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import ForgotPassword from '../views/ForgotPassword.vue'
import Dashboard from '../views/Dashboard.vue'
import PlantList from '@/views/PlantList.vue'
import BatchImport from '../views/BatchImport.vue'
import ComponentList from '../views/ComponentList.vue'
import AchievementList from '../views/AchievementList.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/forgot-password',
    name: 'ForgotPassword',
    component: ForgotPassword
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true }
  },
  {
    path: '/plants',
    name: 'PlantList',
    component: PlantList,
    meta: { requiresAuth: true }
  },
  {
    path: '/plants/add',
    name: 'AddPlant',
    component: () => import('@/views/AddPlant.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/plants/import',
    name: 'BatchImport',
    component: BatchImport,
    meta: { requiresAuth: true }
  },
  {
    path: '/plants/:id',
    name: 'PlantDetail',
    component: () => import('@/views/PlantDetail.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/plants/:id/edit',
    name: 'EditPlant',
    component: () => import('@/views/EditPlant.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/components',
    name: 'ComponentList',
    component: ComponentList,
    meta: { requiresAuth: true }
  },
  {
    path: '/achievements',
    name: 'AchievementList',
    component: AchievementList,
    meta: { requiresAuth: true }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const isAuthenticated = !!localStorage.getItem('token')
  
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next('/login')
    } else {
      next()
    }
  } else {
    if (isAuthenticated && (to.path === '/login' || to.path === '/forgot-password')) {
      next('/dashboard')
    } else {
      next()
    }
  }
})

export default router 